#include "mainwindow.h"
#include <QApplication>
#include <QDesktopWidget>
#include "systemfile.h"
#include <QMutex>
#include <QSystemSemaphore>
#include <QSharedMemory>
#include <QMessageBox>
#include "login.h"
systemFile *sysInfo;
bool WinShowFlag;
QString USER;
QString USERTYPE;
void outputMessage(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
    static QMutex mutex;
    mutex.lock();

    QString text;
    switch(type)
    {
    case QtDebugMsg:
        text = QString("Debug:");
        break;

    case QtWarningMsg:
        text = QString("Warning:");
        break;

    case QtCriticalMsg:
        text = QString("Critical:");
        break;

    case QtFatalMsg:
        text = QString("Fatal:");
    }

    QString context_info = QString("File:(%1) Line:(%2)").arg(QString(context.file)).arg(context.line);
    QString current_date_time = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss ddd");
    QString current_date = QString("(%1)").arg(current_date_time);
    QString message = QString("%1 %2 %3 %4").arg(text).arg(context_info).arg(current_date).arg(msg);
    QString logname =QDate::currentDate().toString("yyyyMMdd").append(".txt");
    QString delename=QDate::currentDate().addDays(-10).toString("yyyyMMdd").append(".txt");

    QFile file(logname);
    file.open(QIODevice::WriteOnly | QIODevice::Append);
    QTextStream text_stream(&file);
    text_stream << message << "\r\n";
   /* if(text_stream.pos() > 100*100 )
    {
         file.resize(text_stream.pos());
         text_stream.seek(0);
         text_stream << QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz") << " ";
         text_stream << endl << "Log file wrapped >>>>>>>>>" << endl << endl;
    }*/
    file.flush();
    file.close();
    mutex.unlock();
    QFile defile(delename);
    if(defile.exists())
    {
     defile.remove();
    }
}

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QSystemSemaphore sema("JAMKey",1,QSystemSemaphore::Open);
    sema.acquire();// 在临界区操作共享内存   SharedMemory
    QSharedMemory mem("SystemObject");// 全局对象名
    if (!mem.create(1))// 如果全局对象以存在则退出
    {
        QMessageBox::information(0,"提示","程序正在使用中，请关闭后再重新打开！");
        sema.release();// 如果是 Unix 系统，会自动释放。
        return 0;
    }
    sema.release();// 临界区
    QApplication::addLibraryPath("./plugins");
    //qInstallMessageHandler(outputMessage);
    sysInfo = new systemFile();
    MainWindow w;
    w.show();
    w.move ((QApplication::desktop()->width() - w.width())/2,(QApplication::desktop()->height() - w.height()-48)/2);
    return a.exec();
}
